<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = [
        'key',
        'display_name',
        'value',
        'group'
    ];
    
    /**
     * 根据键获取设置值
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function getValue($key, $default = null)
    {
        $setting = self::where('key', $key)->first();
        return $setting ? $setting->value : $default;
    }
    
    /**
     * 设置键值对
     *
     * @param string $key
     * @param mixed $value
     * @param string $displayName
     * @param string $group
     * @return Setting
     */
    public static function setValue($key, $value, $displayName = null, $group = 'general')
    {
        $setting = self::firstOrNew(['key' => $key]);
        $setting->value = $value;
        
        if ($displayName) {
            $setting->display_name = $displayName;
        }
        
        if (!$setting->exists) {
            $setting->display_name = $displayName ?: $key;
            $setting->group = $group;
        }
        
        $setting->save();
        return $setting;
    }
}
